﻿CREATE FUNCTION [QIC].[CallFactory_V](@Token QIC.TokenTable READONLY, @CallerId INT, @CalleeId INT, @ReturnPropertName VARCHAR(50), @TokenMap VARCHAR(50), @Indent INT, @CalleeDelegateName varchar(50))
RETURNS VARCHAR(MAX)
AS
BEGIN

	DECLARE @Call VARCHAR(MAX) 
	DECLARE @ReturnMap VARCHAR(MAX)
	DECLARE @LocalToken QIC.TokenTable

	IF @CalleeId IS NULL OR @CallerId = @CalleeId
	BEGIN
		SET @ReturnMap = ''
		SELECT @ReturnMap += 'CAST(NULL AS ' + QIC.TokenDefine('',Targetcolumns.user_type_id, Targetcolumns.precision, Targetcolumns.scale, Targetcolumns.max_length,0,0)  + ') AS ' + QIC.FormatArg(Targetcolumns.name) + ', '
		FROM sys.columns Targetcolumns
		WHERE Targetcolumns.object_id = @CallerId
		ORDER BY Targetcolumns.column_id

		IF @ReturnMap <> '' SET @ReturnMap = LEFT(@ReturnMap,DATALENGTH(@ReturnMap) - 2)
		SET @ReturnMap = ISNULL(@ReturnMap,'')

		SET @Call = ''
		SET @Call += QIC.Indent(@Indent) + 'SELECT ' + @ReturnMap

	END
	ELSE
	BEGIN
		INSERT INTO @LocalToken (IsOutPut,IsReadOnly,MaxLength,ObjectId,Precision,PropertyId,PropertyName,Scale,UserTypeId)
		SELECT 0,0,0,ObjectId,0,PropertyId,PropertyName,0,0 FROM @Token WHERE ObjectId = @CalleeId

		SET @ReturnMap = ''
		SELECT @ReturnMap += 
			CASE Targetcolumns.name 
			WHEN 'DelegateName' THEN QUOTENAME(@CalleeDelegateName,'''')
			ELSE
				CASE ISNULL(SourceColumns.name, QIC.TokenSubstitute(@LocalToken, Targetcolumns.name, @TokenMap)) 
					WHEN 'NULL' THEN 'CAST(NULL AS ' + QIC.TokenDefine('',Targetcolumns.user_type_id, Targetcolumns.precision, Targetcolumns.scale, Targetcolumns.max_length,0,0)  + ')'
					ELSE QIC.FormatArg(ISNULL(SourceColumns.name, QIC.TokenSubstitute(@LocalToken, Targetcolumns.name, @TokenMap)))
				END 
			END
			+ ', '
		FROM sys.columns Targetcolumns
		LEFT OUTER JOIN sys.columns SourceColumns
			ON SourceColumns.object_id = @CalleeId
			AND QIC.TokenSubstitute(@LocalToken, SourceColumns.name, @TokenMap) =  Targetcolumns.name
		WHERE Targetcolumns.object_id = @CallerId
		ORDER BY Targetcolumns.column_id

		IF @ReturnMap <> '' SET @ReturnMap = LEFT(@ReturnMap,DATALENGTH(@ReturnMap) - 2)
		SET @ReturnMap = ISNULL(@ReturnMap,'')


		SET @Call = ''
		SET @Call += QIC.Indent(@Indent) + 
			'SELECT ' + @ReturnMap + ' FROM ' + 
			QIC.ObjectName(@CalleeId) 
	END

	RETURN @Call

END
